<?php

// WebPage类
class WebPageAction extends Action {


	//$kw:根据输入的关键字和文字的标题匹配
	public function index($kw='',$order="updateTime", $orderBy="desc", $start=0, $limit=25) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$WebPageModel = M("web_page");
		$where["deleted"] = 0;
		if(!empty($kw)){
			$where["title"] = array("like","%".trim($kw)."%");
		}
		$arr = $WebPageModel->where($where)->order("$order $orderBy")->limit("$start,$limit")->select();

		if ($arr) {
			$cid = Session::$user["customerId"];
			if($cid == 0){
				$prefix = C('ORIGINAL_DB_PREFIX');
			} else {
				$prefix = C('ORIGINAL_DB_PREFIX').$cid.'_';
			}
			for($i = 0; $i < count($arr); $i++) {
				$tags = "";
				$webPageId = $arr[$i]["id"];
				$TagListModel = M("web_page_tag_list");
				$arrTag = $TagListModel->alias("taglist")->where("webPageId=$webPageId")
					->join($prefix . 'web_page_tag tag ON taglist.tagId=tag.id')->field("taglist.*,tag.tagName")->select();
				foreach ($arrTag as $tag) {
					$tags .= $tag["tagName"] . ',';
				}
				if (count($arrTag) > 0) {
					$tags = substr($tags, 0, strlen($tags) - 1);
				}
				$arr[$i]["tags"] = $tags;
			}
			Output::instance()->objArray($arr, $WebPageModel->where($where)->count());
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	//获取文章模版列表
	public function getTemplateList() {
		$tplModel = M("pb_template");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$where["module"]="webPage";
		$arr = $tplModel->where($where)->select();
		if ($arr) {
			Output::instance()->objArray($arr);
		} else {
			Output::instance()->resultCode();
		}
	}

	//根据模板id获取单个模版信息
	public function getTemplateById($id) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$tempModel = M("pb_template");
		$res = $tempModel ->where("id=$id")->find();
		Session::switchCustomer($cid);
		if ($res!==false) {
			Output::instance()->object($res);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	//获取文章标签模版列表
	public function getWebPageTagTemplateList(){
		$tplModel = M("webpage_tag_template");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$arr = $tplModel->select();
		if ($arr) {
			Output::instance()->objArray($arr);
		} else {
			Output::instance()->resultCode();
		}
	}

	//根据模板id获取单个标签模版信息
	public function getWebPageTagTemplateById($id) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$tempModel = M();
		$res = $tempModel ->query('select * from wx_webpage_tag_template where id ='.$id);
		//echo $tempModel->getLastSql();
		if ($res!==false) {
			Output::instance()->object($res);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	public function getWebPageById($id) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$WebPageModel = M("web_page");
		$where["deleted"] = array('eq',0);
		$where["id"] = array('eq',$id);
		$webpage = $WebPageModel->where($where)->find();

		if ($webpage) {
			$cid = Session::$user["customerId"];
			if($cid == 0){
				$prefix = C('ORIGINAL_DB_PREFIX');
			} else {
				$prefix = C('ORIGINAL_DB_PREFIX').$cid.'_';
			}
			$tags = "";
			$webPageId = $webpage["id"];
			$TagListModel = M("web_page_tag_list");
			$arrTag = $TagListModel->alias("taglist")->where("webPageId=$webPageId")
				->join($prefix . 'web_page_tag tag ON taglist.tagId=tag.id')
				->field("taglist.*,tag.tagName,GROUP_CONCAT(tag.id) as tagIds")
				->find();

// 			foreach ($arrTag as $tag) {
// 				$tags .= $tag["tagName"] . ',';
// 			}
// 			if (count($arrTag) > 0) {
// 				$tags = substr($tags, 0, strlen($tags) - 1);
// 			}

			if($arrTag){
				$webpage["tags"] = $arrTag["tagIds"];
			}else{
				$webpage["tags"] = NULL;
			}

			$AttachMentModel = M("web_page_attachment");
			$attach = $AttachMentModel->where("webPageId=$webPageId")
			->field("GROUP_CONCAT(url) as attachmentsUrl,GROUP_CONCAT(attachmentName) as attachmentsName,GROUP_CONCAT(id) as attachmentsId")
			->find();

			if($attach){
				$webpage["attachmentsName"] = $attach["attachmentsName"];
				$webpage["attachmentsUrl"] = $attach["attachmentsUrl"];
				$webpage["attachmentsId"] = $attach["attachmentsId"];
			}else{
				$webpage["attachmentsName"] = NULL;
				$webpage["attachmentsUrl"] = NULL;
				$webpage["attachmentsId"] = NULL;
			}


			Output::instance()->object($webpage);

		} else {
			Output::instance()->resultCode(code_success);
		}
	}


	public function save($id,$title, $picurl, $description, $content, $rate, $comment,
			$stickyPost, $readAccess, $attachmentsUrl, $attachmentsName, $tags,$accessTag,
			$author=null, $focusLink=null, $weixinName=null, $isDisplayReadCount=null, $bgColor = null, $tplid=1) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$WebPageModel = M("web_page");
		$data["tplid"] = $tplid;
		$time = date("Y-m-d H:i:s");
		$data["title"] = $title;
		$data["picurl"] = $picurl;
		$data["description"] = $description;
		$data["content"] = $content;
		$data["attachmentCount"] = count(explode(",", $attachmentsUrl));
		$data["rate"] = $rate === 'true'? true: false;
		$data["comment"] = $comment  === 'true'? true: false;
		$stickyPost = $stickyPost === 'true'? true: false;
        $data['author'] = $author;
        $data['focusLink'] = $focusLink;
        $data['weixinName'] = ($weixinName != null) ? $weixinName : "";
        $data['isDisplayReadCount'] = ($isDisplayReadCount != null) ? $isDisplayReadCount : 0;
        $data['bgColor'] = $bgColor;
		$data["stickyPost"] = $stickyPost;

		if ($stickyPost) {
			$data["stickyPostTime"] = $time;
		} else {
			$data["stickyPostTime"] = null;
		}
		$data["readAccess"] = $readAccess;
		$data["accessTag"] = $accessTag;
		//-----ihziluo添加标签
		if(!empty($accessTag)){
			addAccessTags($accessTag);
		}
		//-----ihziluo添加标签
		$data["updateTime"] = $time;
        $data["createTime"] = $time;
        if($id) {
			$data["id"]=$id;
        	$result = $WebPageModel->save($data);
        } else {
			$result = $WebPageModel->add($data);
        }
		if ($result!==false) {
			// add attachement
			$AttachMentModel = M("web_page_attachment");

			$AttachMentModel->where("webPageId=$result")->delete();
			if($attachmentsUrl != '' && $attachmentsName !=''){

				$arrAtt = explode(",", $attachmentsUrl);
				$arrAttName = explode(",", $attachmentsName);

				if (count($arrAtt) == count($arrAttName)) {
					for ($i = 0; $i < count($arrAtt); $i++) {
						$dataAtt["webPageId"] = $id;
						$dataAtt["url"] = $arrAtt[$i];
						$dataAtt["attachmentName"] = $arrAttName[$i];
						$AttachMentModel->add($dataAtt);
					}
				} else {
					Log::write("WebPage Add 附件参数错误");
				}
			}



			$TagModel = M("web_page_tag");
			$arrTag = explode(",", $tags);

			$TagListModel = M("web_page_tag_list");
			$arrTag = explode(",", $tags);
				$TagListModel->where("webPageId=$id")->delete();
				if($tags != ''){
					foreach ($arrTag as $tagId) {
						$dataTagList["tagId"] = $tagId;
						$dataTagList["webPageId"] = $id;
						$TagListModel->add($dataTagList);
					}
				}

			$data["tags"] = $tags;
// 			$data["attachments"] = $attachments;
			$data["id"] = $result;
			Output::instance()->object($data);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	public function delete($id) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$WebPageModel = M("web_page");
		$result = $WebPageModel->where("id=$id")->setField("deleted", 1);

		if ($result) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	public function getAttachMent($webPageId) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$AttachMentModel = M("web_page_attachment");
		$arr = $AttachMentModel->where("webPageId=$webPageId")->order("id asc")->select();
		if ($arr) {
			Output::instance()->objArray($arr);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}

	public function getTag($order = "number", $orderBy ="asc", $start = 0, $limit = 25) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$TagModel = M("web_page_tag");
		$arr = $TagModel->order("$order $orderBy")->limit("$start, $limit")->select();
		if ($arr) {
			$count = $TagModel->count();
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	public function getWebpageByTagId($tagId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		$webPage = M("web_page");
		$webPageTag = M("web_page_tag");
		$count = $webPage->alias("a")
					->join("inner join wx_".$cid."_web_page_tag_list b on a.id = b.webPageId")
					->join("inner join wx_".$cid."_web_page_tag c on c.id = b.tagId")
					->where("c.id=".$tagId)->count();
		$result['total'] = $count;
		Output::instance()->Object($result);
	}
	//文章标签添加
	public function addTag($tagName,$number=0,$userUpload=0,$tplid=1,$picUrl='',$description=''){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$WebpageTagModel = M("web_page_tag");
		$where['tagName'] = $tagName;
		$webpagetag = $WebpageTagModel->where($where)->find();
		if($webpagetag){
			Output::instance()->resultCode(code_webpage_add_tag_exist);
			return;
		}
		$add['tagName'] = $tagName;
		$add['number']=$number;
		$add['userUpload']=$userUpload;
		$add['picUrl']=$picUrl;
		$add['description']=$description;
		$add['tagtplid']=$tplid;
		$addTag = $WebpageTagModel->add($add);
		$out=new StdClass();
		$out->code=0;
		$out->id=$addTag;
		if ($addTag) {
			Output::instance()->object($out);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}

	}
	//获得标签下文章列表
	public function getTagListById($id,$limit,$phone=false){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		$webPage = M("web_page");
		if($limit){
			$out = $webPage->alias("a")
					->join("inner join wx_".$cid."_web_page_tag_list b on a.id = b.webPageId")
					->join("inner join wx_".$cid."_web_page_tag c on c.id = b.tagId")
					->field("b.webPageId as id,a.picurl")
					->where("c.id=".$id)->limit("0, $limit")->select();
		}else{
			$out = $webPage->alias("a")
					->join("inner join wx_".$cid."_web_page_tag_list b on a.id = b.webPageId")
					->join("inner join wx_".$cid."_web_page_tag c on c.id = b.tagId")
					->field("b.webPageId as id,a.picurl")
					->where("c.id=".$id)->select();
		}
		$count =  $webPage->alias("a")
					->join("inner join wx_".$cid."_web_page_tag_list b on a.id = b.webPageId")
					->join("inner join wx_".$cid."_web_page_tag c on c.id = b.tagId")
					->where("c.id=".$id)->count();
		$result["total"] = $count;
		$result['contentList'] = $out;
		if($phone){
			return $result;
		}else{
			if ($out) {
				Output::instance()->object($result);
			} else {
				Output::instance()->resultCode(code_success);
			}
		}
	}

	public function getTagById($id,$phone=false) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$TagModel = M("web_page_tag");
		$condition["id"] = array("eq",$id);
		$tag = $TagModel->where($condition)->find();
		if($phone){
			return $tag;
		}else{
			if ($tag) {
				Output::instance()->object($tag);
			} else {
				Output::instance()->resultCode(code_success);
			}
		}

	}


	public function updateTag($id, $tagName, $number,$tplid='', $picUrl = NULL,$description=NULL,$userUpload = false) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		if(trim($tplid) ==0 || trim($tplid) ==''){
			$tplid =1;
		}
		$TagModel = M("web_page_tag");
		$data["tagName"] = $tagName;
		$data["number"]= $number;
		$data["picUrl"] = $picUrl;
		$data["description"] = $description;
		$data["userUpload"] = $userUpload;
		$data["tagtplid"] = $tplid;
		$result = $TagModel->where("id=$id")->save($data);
		//echo $TagModel ->getLastSql();
		// 		if ($result) {
		$data["id"] = $id;
		Output::instance()->object($data);
		// 		} else {
		// 			Output::instance()->resultCode(code_sql_error);
		// 		}

	}

	public function deleteTag($id) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$TagModel = M("web_page_tag");
		$result = $TagModel->where("id=$id")->delete();
		if ($result) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	public function getWebpageRepost($order = 'updateTime', $orderBy = 'desc', $start = 0, $limit = 25) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$RepostModel = M("web_page_event");
		$where["fromCustomerId"] = $customerId;
		$where["deleted"] = 0;
		$result = $RepostModel->where($where)->order("$order $orderBy")->limit($start, $limit)->select();
		if ($result) {
			$count = $RepostModel->where($where)->count();
			Output::instance()->objArray($result, $count);
		} else {
			Output::instance()->resultCode();
		}

		Session::switchCustomer($customerId);
	}

	public function addWebpageRepost($webPageId, $webPageTitle, $eventId = NULL, $eventName = NULL, $eventType = REPOST_TYPE_WEBPAGE) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$RepostModel = M("web_page_event");
		$data["fromCustomerId"] = $customerId;
		$data["webPageId"] = $webPageId;
		$data["webPageTitle"] = $webPageTitle;
		$data["eventId"] = $eventId;
		$data["eventName"] = $eventName;
		$data["eventType"] = $eventType;
		$data["updateTime"] = date("Y-m-d H:i:s");
		$result = $RepostModel->add($data);
		if ($result) {
			$data["id"] = $result;
			Output::instance()->object($data);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
		Session::switchCustomer($customerId);
	}

	public function deleteWebpageRepost($id) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$RepostModel = M("web_page_event");
		$where["id"] = $id;
		$result = $RepostModel->where($where)->setField('deleted', 1);
		if ($result) {
			Output::instance()->resultCode();
		} else {
			Output::instance()->resultCode(code_sql_error);
		}

		Session::switchCustomer($customerId);
	}

	public function getWebPageRepostStatistics($webPageId, $start = 0, $limit = 25) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$RepostModel = M("web_page_repost_view");
		$where["fromCustomerId"] = $customerId;
		$where["webPageId"] = $webPageId;

		$isApiAuth = Session::$user['isApiAuth'];
		if($isApiAuth){//有高级接口
			$arr = $RepostModel->alias("repost")->where($where)
				->group('srcFromUserName')
				->join("wx_" . $customerId . "_web_page page ON repost.webPageId = page.id")
				->join('LEFT JOIN wx_'.$customerId.'_user_info uinfo on uinfo.fromUserName = user.userName')
				->join('LEFT JOIN wx_'.$customerId.'_user_weixin_info winfo on winfo.openid = user.userName')
				->field("count(*) as repostCount, page.title as webPageTitle, uni.id, winfo.nickname as fullName, uinfo.phone, winfo.headimgurl as picUrl")
				->order("repostCount desc")->limit("$start, $limit")->select();
		} else {
			$arr = $RepostModel->alias("repost")->where($where)->group('srcFromUserName')
			->join("wx_" . $customerId . "_web_page page ON repost.webPageId = page.id")
			->join('LEFT JOIN wx_'.$customerId.'_user_info uinfo on uinfo.fromUserName = user.userName')
			->field("count(*) as repostCount, page.title as webPageTitle, uni.id as uid, uinfo.fullName,uinfo.phone,uinfo.picUrl")
			->order("repostCount desc")->limit("$start, $limit")->select();
		}
// 		echo $RepostModel->getLastSql();
		if ($arr) {
			$count = $RepostModel->alias("repost")->where($where)->count('DISTINCT srcFromUserName');
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode();
		}

		Session::switchCustomer($customerId);
	}

	//ihziluoh添加密友圈tag管理

	public function miGetTag($order = "number", $orderBy ="asc", $start = 0, $limit = 25,$isAll=1) {
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $cid = Session::$user["customerId"];
	    Session::switchCustomer(0);
	    $TagModel = M("micontent_tag");
	    Session::switchCustomer($cid);
		$where['a.fromCustomerId']=array("eq",$cid);
		$where['a.deleted']=array("eq", 0);
		if($isAll){
			$arr = $TagModel->alias('a')->where($where)->join("wx_micontent_tag_group as b on a.groupId=b.id")->order("$order $orderBy")->join("wx_pb_template as c on a.tagtplid=c.id")->field('a.*,b.groupName,c.tplname')->select();
		}else{
			$arr = $TagModel->alias('a')->where($where)->join("wx_micontent_tag_group as b on a.groupId=b.id")->order("$order $orderBy")->join("wx_pb_template as c on a.tagtplid=c.id")->limit("$start, $limit")->field('a.*,b.groupName,c.tplname')->select();
		}
		if ($arr) {
			$count = $TagModel->where($where)->count();
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	//标签下文章数
	public function getContentCount($tagId,$limit=null,$isPhone=false){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$contentModel = M("micontent");
		$contentTag = M("micontent_tag");
		Session::switchCustomer($cid);
		if($limit){
			$list = $contentModel->where("find_in_set($tagId,tags) and deleted=0")->field("id,picUrl,title")->order("updateTime desc")->limit(0,$limit)->select();
		}else{
			$list = $contentModel->where("find_in_set($tagId,tags) and deleted=0")->field("id,picUrl,title")->order("updateTime desc")->select();
		}
		foreach($list as $key=>$value){
			$tagList = $contentTag->alias("a")
				->join("inner join wx_micontent_tag_list b on a.id=b.tagId")
				->where("b.webPageId=".$value['id'])
				->field('tagName')
				->select();
			$list[$key]['tagList']=$tagList;
		}
		$count = $contentModel->where("find_in_set($tagId,tags) and deleted=0")->count();
		$result['total']=$count;
		$result['contentList']=$list;
		if($isPhone){
			return $result;
		}else{
			Output::instance()->object($result);
		}
	}

	//素材标签添加
	public function miAddTag($tagName,$number=0,$userUpload=0,$tplid=1,$picUrl='',$description='',$groupId=''){
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $cid = Session::$user["customerId"];
	    Session::switchCustomer(0);
	    $WebpageTagModel = M("micontent_tag");
	    $WebpageTagGroupModel = M("micontent_tag_group");
	    Session::switchCustomer($cid);
		$where['fromCustomerId']=$cid;
	    $where['tagName'] = $tagName;
	    $webpagetag = $WebpageTagModel->where($where)->find();
	    if($webpagetag){
	        Output::instance()->resultCode(code_webpage_add_tag_exist);
	        return;
	    }
		$add['fromCustomerId']=$cid;
	    $add['tagName'] = $tagName;
	    $add['number']=$number;
	    $add['userUpload']=$userUpload;
	    $add['picUrl']=$picUrl;
	    $add['description']=$description;
	    $add['tagtplid']=$tplid;
		if(!$groupId){
			$groupId=$WebpageTagGroupModel->where("groupName='默认' and cId=$cid")->field("id")->find();
			$groupId= $groupId['id'];
		}
		if(!$groupId){
			$data['groupName']='默认';
			$data['deleted']=0;
			$data['cid']=$cid;
			$data['createTime']=date("Y-m-d H:i:s");
			$groupId = $WebpageTagGroupModel->add($data);
		}
		$add['groupId']=$groupId;
	    $addTag = $WebpageTagModel->add($add);
		$out=new StdClass();
		$out->code=0;
		$out->id=$addTag;
	    if ($addTag) {
            $sql = $WebpageTagModel->getLastSql();
            R('Log/add',array('articleLabel', '', '文章标签', op_add, $sql, '添加文章标签：' . $tagName));
	        Output::instance()->object($out);
	    } else {
	        Output::instance()->resultCode(code_sql_error);
	    }

	}




	public function miGetTagById($id,$isPhone=false) {
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $cid = Session::$user["customerId"];
	    Session::switchCustomer(0);
	    $TagModel = M("micontent_tag");
	    Session::switchCustomer($cid);
	    $condition["a.id"] = array("eq",$id);
	    $tag = $TagModel->alias('a')->where($condition)->join("wx_micontent_tag_group as b on a.groupId=b.id")->field('a.*,b.groupName')->find();
		if($isPhone){
			return $tag;
		}else{
			if ($tag) {
				Output::instance()->object($tag);
			} else {
				Output::instance()->resultCode(code_success);
			}
		}
	}






	public function miUpdateTag($id, $tagName, $number,$tplid='', $picUrl = NULL,$description=NULL,$userUpload = false,$groupId='') {
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    if(trim($tplid) ==0 || trim($tplid) ==''){
	        $tplid =1;
	    }
	    $cid = Session::$user["customerId"];
	    Session::switchCustomer(0);
	    $TagModel = M("micontent_tag");
		$WebpageTagGroupModel = M("micontent_tag_group");
		Session::switchCustomer($cid);
	    $data["tagName"] = $tagName;
	    $data["number"]= $number;
	    $data["picUrl"] = $picUrl;
	    $data["description"] = $description;
	    $data["userUpload"] = $userUpload;
	    $data["tagtplid"] = $tplid;
		if(!$groupId){
			$groupId=$WebpageTagGroupModel->where("groupName='默认' and cId=$cid")->field("id")->find();
			$groupId= $groupId['id'];
		}
		if(!$groupId){
			$data['groupName']='默认';
			$data['deleted']=0;
			$data['cid']=$cid;
			$data['createTime']=date("Y-m-d H:i:s");
			$groupId = $WebpageTagGroupModel->add($data);
		}
		$data["groupId"] = $groupId;
	    $result = $TagModel->where("id=$id")->save($data);
	    //echo $TagModel ->getLastSql();
	    // 		if ($result) {
	    $data["id"] = $id;
        $sql = $TagModel->getLastSql();
        R('Log/add',array('articleLabel', '', '文章标签', op_update, $sql, '更新文章标签：' . $tagName));
	    Output::instance()->object($data);
	    // 		} else {
	    // 			Output::instance()->resultCode(code_sql_error);
	    // 		}

	}

	public function miDeleteTag($id) {
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $cid = Session::$user["customerId"];
	    Session::switchCustomer(0);
	    $TagModel = M("micontent_tag");
	    Session::switchCustomer($cid);
	    $result = $TagModel->where("id=$id")->delete();
        $sql = $TagModel->getLastSql();
        $tagName = $TagModel->where("id=$id")->getField('tagName');
	    if ($result) {
            R('Log/add',array('articleLabel', '', '文章标签', op_delete, $sql, '删除文章标签：' . $tagName));
	        Output::instance()->resultCode(code_success);
	    } else {
	        Output::instance()->resultCode(code_sql_error);
	    }
	}
	//ihziluoh添加密友圈tag管理 end


	/**
	 * 获取文章一二级分组标签
	 */
	public function getContentTag()
	{
		/**1.判断用户是否登录*/
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/**2.实例化数据库表*/
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$miContentTagGroupModel = M('micontent_tag_group');
		$miContentTagModel = M('micontent_tag');
		Session::switchCustomer($cid);

		/**3.查询数据*/
		$where['cid'] = array('eq', $cid);
		$where['deleted'] = array('eq', 0);
		$arr = $miContentTagGroupModel->where($where)->select();
		foreach ($arr as $k => $v) {
			$tag = $miContentTagModel->where(['groupId' => $v['id']])->select();
			$arr[$k]['tag'] = $tag;
		}

		/**4.返回数据*/
		if (!empty($arr)) {
			$Out = [
				'code' => 0,
				'msg' => '获取分组标签成功',
				'data' => $arr,
			];
			Output::instance()->object($Out);
		} else {
			$Out = [
				'code' => 1,
				'msg' => '获取分组标签失败',
				'data' => [],
			];
			Output::instance()->object($Out);
		}

	}

	/**
	 * 文章二级标签列表
	 */
	public function contentTagList($keyword = '',$start = 0, $limit = 10)
	{
		/**1.判断用户是否登录*/
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/**2.实例化数据库表*/
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$miContentTagModel = M('micontent_tag');
		Session::switchCustomer($cid);

		/**3.查询数据*/
		$where['groups.cid'] = array('eq', $cid);
		$where['tag.deleted'] = array('eq', 0);
		empty($keyword) ? '' : $where['tag.tagName'] = array('like', '%' . $keyword . '%');
		$arr = $miContentTagModel->alias('tag')->where($where)->join("wx_micontent_tag_group as groups On tag.groupId=groups.id")->join("wx_pb_template as tpl on tag.tagtplid=tpl.id")->field('tag.*,groups.groupName,tpl.tplname')->order('id desc')->limit($start,$limit)->select();
		$count = $miContentTagModel->alias('tag')->where($where)->join("wx_micontent_tag_group as groups On tag.groupId=groups.id")->join("wx_pb_template as tpl on tag.tagtplid=tpl.id")->field('tag.*,groups.groupName,tpl.tplname')->count();

		/**4.返回数据*/
		if (!empty($arr)) {
			$Out = [
				'code' => 0,
				'msg' => '获取分组标签列表成功',
				'data' => $arr,
				'count' => $count,
			];
			Output::instance()->object($Out);
		} else {
			$Out = [
				'code' => 1,
				'msg' => '获取分组标签列表失败',
				'data' => [],
				'count' => $count,
			];
			Output::instance()->object($Out);
		}
	}

	/**
	 * 文章一级分类添加/修改
	 */
	public function contentTagGroupAdd($id = '', $groupName)
	{
		/**1.判断用户是否登录*/
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/**2.实例化数据库表*/
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$miContentTagGroupModel = M('micontent_tag_group');
		Session::switchCustomer($cid);


		/**3.添加一级分类*/
		$data['groupName'] = $groupName;
		if ($id) {
			$result = $miContentTagGroupModel->where(['id' => $id])->save($data);
		} else {
			$data['cid'] = $cid;
			$data['deleted'] = 0;
			$data['createTime'] = date('Y-m-d H:i:s');
			$result = $miContentTagGroupModel->add($data);
		}
        $sql = $miContentTagGroupModel->getLastSql();

		/**4.判断是否添加成功*/
		if (is_numeric($result)) {
            if (!$id) {
                R('Log/add',array('articleLabel', '', '文章标签', op_add, $sql, '添加文章标签分组：' . $groupName));
            } else {
                R('Log/add',array('articleLabel', '', '文章标签', op_update, $sql, '更新文章标签分组：' . $groupName));
            }
			$Out = [
				'code' => 0,
				'msg' => '添加成功',
				'data' => []
			];
			Output::instance()->object($Out);
			return;
		} else {
			$Out = [
				'code' => 1,
				'msg' => '添加失败',
				'data' => []
			];
			Output::instance()->object($Out);
			return;
		}

	}

	/**
	 * 删除文章一级标签
	 * @param $id      标签id
	 */
	public function contentTagGroupDelete($id)
	{
		/**1.判断用户是否登录*/
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		/**2.实例化数据库表*/
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$micontentTagGroupModel = M('micontent_tag_group');
		Session::switchCustomer($cid);

		/**3.删除标签*/
		$result = $micontentTagGroupModel->where("id=$id")->setField('deleted', 1);
        $sql = $micontentTagGroupModel->getLastSql();
        $groupName = $micontentTagGroupModel->where("id=$id")->getField('groupName');

		/**4.判断是否删除成功*/
		if ($result) {
            R('Log/add',array('articleLabel', '', '文章标签', op_delete, $sql, '删除文章标签分组' . $groupName));
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	/**
	 * 文章一级分类详情
	 * @param $id
	 */
	public function contentTagGroupDetail($id)
	{
		/**1.判断用户是否登录*/
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		/**2.实例化数据库表*/
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$micontentTagGroupModel = M('micontent_tag_group');
		Session::switchCustomer($cid);

		/**3.删除标签*/
		$arr = $micontentTagGroupModel->where("id=$id")->find();

		/**4.返回数据*/
		if (!empty($arr)) {
			$Out = [
				'code' => 0,
				'msg' => '获取分组标签列表成功',
				'data' => $arr,
			];
			Output::instance()->object($Out);
		} else {
			$Out = [
				'code' => 1,
				'msg' => '获取分组标签列表失败',
				'data' => [],
			];
			Output::instance()->object($Out);
		}
	}

	/**
	 * 文章一级分类列表
	 * @param $id
	 */
	public function contentGroupList($keyword = '', $start = 0, $limit = 10)
	{
		/**1.判断用户是否登录*/
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		/**2.实例化数据库表*/
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$micontentTagGroupModel = M('micontent_tag_group');
		Session::switchCustomer($cid);

		empty($keyword) ? '' : $where['groupName'] = array("like","%".trim($keyword)."%");
		$where['deleted'] = array("eq", 0);
		$where['cid'] = array("eq", $cid);


		/**3.删除标签*/
		$arr = $micontentTagGroupModel->where($where)->limit($start,$limit)->select();
		$count = $micontentTagGroupModel->where($where)->count();

		/**4.返回数据*/
		if (!empty($arr)) {
			$Out = [
				'code' => 0,
				'msg' => '获取分组标签列表成功',
				'data' => $arr,
				'count' => $count
			];
			Output::instance()->object($Out);
		} else {
			$Out = [
				'code' => 1,
				'msg' => '获取分组标签列表失败',
				'data' => [],
			];
			Output::instance()->object($Out);
		}
	}

}